
const request = require('../../utils/request');
const buildUrl = request.buildUrl || ((url) => url);

Page({
  data: {
    // 筛选条件
    timeRange: 'week',
    startDate: '',
    endDate: '',
    incomeTypeFilter: 'all',
    minAmount: '',
    maxAmount: '',
    statusFilter: 'all',
    showFilterModal: false,

    // 收入数据
    incomeStats: {
      availableBalance: 0,
      totalIncome: 0,
      todayIncome: 0,
      monthIncome: 0,
      totalOrders: 0
    },

    // 收入列表
    incomeList: [],

    // 图表数据
    chartData: {
      period: '本周',
      bars: []
    },

    // 分页
    page: 1,
    pageSize: 10,
    hasMore: true
  },

  onLoad() {
    this.initDates();
    this.loadIncomeData();
  },

  onShow() {
    this.refreshIncomeData();
  },

  // 初始化日期
  initDates() {
    const today = new Date();
    const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

    this.setData({
      startDate: this.formatDate(oneWeekAgo),
      endDate: this.formatDate(today)
    });
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 加载收入数据
  async loadIncomeData() {
    const app = getApp();
    const userId = app.globalData.userId;

    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    try {
      // 获取收入统计
      const statsRes = await this.request({
        url: `/api/courier-users/income/${userId}`,
        method: 'GET'
      });

      if (statsRes.success) {
        this.setData({
          incomeStats: statsRes.data
        });
      }

      // 获取收入记录
      await this.loadIncomeList();

      // 获取图表数据
      await this.loadChartData();

    } catch (error) {
      console.error('加载收入数据失败:', error);
      wx.showToast({ title: '数据加载失败', icon: 'none' });
    }
  },

  // 加载收入记录
  async loadIncomeList() {
    try {
      const res = await request({
        url: '/api/incomes',
        method: 'GET'
      });

      console.log('💰 收入数据:', res);

      let incomeList = [];
      if (res.success) {
        // 处理不同的数据结构
        if (Array.isArray(res.data)) {
          incomeList = res.data;  // 直接是数组
        } else if (res.data && Array.isArray(res.data.list)) {
          incomeList = res.data.list;  // 包含list属性
        }
      }

      this.setData({
        incomeList: incomeList,
        loadingIncomeList: false
      });
    } catch (err) {
      console.error('加载收入记录失败:', err);
      this.setData({
        incomeList: [],
        loadingIncomeList: false
      });
    }
  },

  // 加载图表数据
  async loadChartData() {
    const app = getApp();
    const userId = app.globalData.userId;

    try {
      const res = await this.request({
        url: `/api/incomes/chart`,
        method: 'GET',
        data: {
          userId: userId,
          timeRange: this.data.timeRange,
          startDate: this.data.startDate,
          endDate: this.data.endDate
        }
      });

      if (res.success) {
        this.setData({
          chartData: {
            period: this.getChartPeriodText(),
            bars: this.processChartData(res.data)
          }
        });
      }
    } catch (error) {
      console.error('加载图表数据失败:', error);
    }
  },

  // 处理图表数据
  processChartData(data) {
    const maxAmount = Math.max(...data.map(item => item.amount));
    return data.map(item => ({
      label: item.label,
      amount: item.amount,
      percentage: maxAmount > 0 ? (item.amount / maxAmount) * 100 : 0,
      color: this.getChartColor(item.amount, maxAmount)
    }));
  },

  // 获取图表颜色
  getChartColor(amount, maxAmount) {
    if (maxAmount === 0) return '#007acc';
    const ratio = amount / maxAmount;
    if (ratio > 0.7) return '#52c41a';
    if (ratio > 0.4) return '#fa8c16';
    return '#ff4d4f';
  },

  // 获取图表周期文本
  getChartPeriodText() {
    const periodMap = {
      'today': '今日',
      'week': '本周',
      'month': '本月',
      'all': '全部',
      'custom': '自定义'
    };
    return periodMap[this.data.timeRange] || '本周';
  },

  // 获取收入类型文本
  getIncomeTypeText(type) {
    const typeMap = {
      'order': '订单收入',
      'withdraw': '提现',
      'bonus': '奖励收入',
      'refund': '退款'
    };
    return typeMap[type] || '其他';
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'completed': '已完成',
      'pending': '处理中',
      'failed': '失败'
    };
    return statusMap[status] || '未知';
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (days === 1) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return `${date.getMonth() + 1}-${date.getDate()}`;
    }
  },

  // 设置时间范围
  setTimeRange(e) {
    const range = e.currentTarget.dataset.range;
    this.setData({ timeRange: range });
    this.refreshIncomeData();
  },

  // 显示自定义日期选择
  showCustomDatePicker() {
    this.setData({ timeRange: 'custom' });
  },

  // 日期变化
  onStartDateChange(e) {
    this.setData({ startDate: e.detail.value });
  },

  onEndDateChange(e) {
    this.setData({ endDate: e.detail.value });
  },

  // 应用自定义日期
  applyCustomDate() {
    this.refreshIncomeData();
  },

  // 显示筛选模态框
  showFilterModal() {
    this.setData({ showFilterModal: true });
  },

  hideFilterModal() {
    this.setData({ showFilterModal: false });
  },

  // 设置收入类型筛选
  setIncomeTypeFilter(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ incomeTypeFilter: type });
  },

  // 金额输入
  onMinAmountInput(e) {
    this.setData({ minAmount: e.detail.value });
  },

  onMaxAmountInput(e) {
    this.setData({ maxAmount: e.detail.value });
  },

  // 设置状态筛选
  setStatusFilter(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({ statusFilter: status });
  },

  // 重置筛选
  resetFilters() {
    this.setData({
      incomeTypeFilter: 'all',
      minAmount: '',
      maxAmount: '',
      statusFilter: 'all'
    });
  },

  // 应用筛选
  applyFilters() {
    this.hideFilterModal();
    this.setData({ page: 1 });
    this.loadIncomeList();
  },

  // 跳转到提现
  goToWithdraw() {
    if (this.data.incomeStats.availableBalance <= 0) {
      wx.showToast({ title: '无可提现余额', icon: 'none' });
      return;
    }
    wx.navigateTo({ url: '/pages/profile/withdraw' });
  },

  // 跳转到接单大厅
  goToOrderHall() {
    const app = getApp();
    app.switchRole('courier');
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 加载更多
  loadMoreIncomes() {
    if (!this.data.hasMore) return;

    this.setData({ page: this.data.page + 1 });
    this.loadIncomeList();
  },

  // 刷新收入数据
  refreshIncomeData() {
    this.setData({ page: 1 });
    this.loadIncomeData();
  },

  // 网络请求封装
  request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: buildUrl(options.url || ''),
        method: options.method || 'GET',
        data: options.data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshIncomeData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});